package com.es.config;

import java.nio.charset.Charset;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import com.es.common.aspect.LoginInterceptor;

/**
 * 
 * 全局跨域
 * @author Administrator
 *https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/EnableWebMvc.html
 */
@Configuration
@ComponentScan(basePackageClasses = Blog2MVCConfig.class)
public class Blog2MVCConfig extends WebMvcConfigurationSupport{

	/**
	 * 跨域访问配置
	 */
	@Override
	protected void addCorsMappings(CorsRegistry registry) {
		
		registry.addMapping("/api")//跨域限定的访问地址
		.allowedOrigins("http://m.womai.com")//限定跨域的域名
		.allowedMethods("GET");//限定跨域的访问方法
	}
	
	/**
	 * 拦截器配置
	 */
	@Override
	protected void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new LoginInterceptor())
		.addPathPatterns("/**")
		.excludePathPatterns("/login","/register");
		super.addInterceptors(registry);
	}
	/**
	 * 格式化配置
	 */
	@Override
	protected void addFormatters(FormatterRegistry registry) {
		// TODO Auto-generated method stub
		super.addFormatters(registry);
	}
	
	/**
	 * url到视图映射
	 */
	@Override
	protected void addViewControllers(ViewControllerRegistry registry) {
		// TODO Auto-generated method stub
		super.addViewControllers(registry);
	}
	
	/**
	 * 处理乱码
	 * @return
	 */
	@Bean
	public HttpMessageConverter<String> responseBodyConverter(){
		StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
		return converter;
	}
	
	@Override
	protected void configureMessageConverters(
			List<HttpMessageConverter<?>> converters) {
		// TODO Auto-generated method stub
		super.configureMessageConverters(converters);
		converters.add(responseBodyConverter());
	}
}
